package com.h3c.ptability.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.util.IdWorker;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eos.common.util.Result;
import com.eos.common.util.UserUtils;
import com.github.pagehelper.PageHelper;
import com.h3c.ptability.cache.DeptCache;
import com.h3c.ptability.client.EosSyncDataClient;
import com.h3c.ptability.dto.PtAllWorkerViewDTO;
import com.h3c.ptability.dto.eos.EosRoleClientDTO;
import com.h3c.ptability.entity.PtAllWorker;
import com.h3c.ptability.entity.PtDept;
import com.h3c.ptability.mapper.PtAllWorkerMapper;
import com.h3c.ptability.service.CommService;
import com.h3c.ptability.service.EosAuthService;
import com.h3c.ptability.service.IPtAllWorkerService;
import com.h3c.ptability.dto.PtAllWorkerDTO;
import com.h3c.ptability.support.PageQuery;
import com.h3c.ptability.utils.AppBusinessException;
import com.h3c.ptability.utils.InitExampleOrderByUtils;
import com.h3c.ptability.utils.MybatisUtils;
import com.h3c.ptability.vo.PtAllWorkerVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: PtAllWorkerServiceImpl
 *
 * @Author: l22886
 * @Date: 2022-03-14
 * Description: pt_all_worker serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
public class PtAllWorkerServiceImpl extends ServiceImpl<PtAllWorkerMapper, PtAllWorker> implements IPtAllWorkerService {

    @Resource
    private PtAllWorkerMapper ptAllWorkerMapper;
    @Autowired
    private IPtAllWorkerService ptAllWorkerService;
    @Resource
    private CommService commService;

    /**
     * EOS相关服务
     */
    @Resource
    private EosAuthService eosAuthService;

    @Autowired
    EosSyncDataClient eosSyncDataClient;

    @Autowired(required = false)
    private UserUtils userUtils;

    @Value("${inventory.account}")
    private String inventoryAccount;

    @Value("${inventory.password}")
    private String inventoryPassword;

    /**
     * @title: selectFuzzyByDto
     * @description: 模糊查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<PtAllWorkerViewDTO> selectFuzzyByDto(PtAllWorkerDTO dto) {
//        List<PtAllWorker> list = ptAllWorkerMapper.selectByExample(initFuzzyExample(dto));
        QueryWrapper<PtAllWorker> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(!StringUtils.isEmpty(dto.getWorkerId()), PtAllWorker::getWorkerId, Arrays.asList(dto.getWorkerId().split(",")))
                .eq(dto.getWorkerStatus() != null, PtAllWorker::getWorkerStatus, dto.getWorkerStatus());
        List<PtAllWorker> list = ptAllWorkerMapper.selectList(queryWrapper);
//        List<PtAllWorker> list = ptAllWorkerMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto),PtAllWorker.class));
//        List<PtAllWorkerViewDTO> list1 = JSONArray.parseArray(JSONArray.toJSONString(list), PtAllWorkerViewDTO.class);
        List<PtAllWorkerViewDTO> list2 = new ArrayList<>();
//        BeanUtils.copyProperties(list,list2);

        list.forEach(ptAllWorker -> {
            PtAllWorkerViewDTO ptAllWorkerViewDTO = new PtAllWorkerViewDTO();
            BeanUtils.copyProperties(ptAllWorker, ptAllWorkerViewDTO);

            if (!StringUtils.isEmpty(ptAllWorkerViewDTO.getDept1id()) && !ObjectUtils.isEmpty(commService.getDept(ptAllWorkerViewDTO.getDept1id()))) {
                ptAllWorkerViewDTO.setDept1name(commService.getDept(ptAllWorkerViewDTO.getDept1id()).getDeptName());
            }
            if (!StringUtils.isEmpty(ptAllWorkerViewDTO.getDept2id()) && !ObjectUtils.isEmpty(commService.getDept(ptAllWorkerViewDTO.getDept2id()))) {
                ptAllWorkerViewDTO.setDept2name(commService.getDept(ptAllWorkerViewDTO.getDept2id()).getDeptName());
            }
            if (!StringUtils.isEmpty(ptAllWorkerViewDTO.getDept1id()) && !ObjectUtils.isEmpty(commService.getDept(ptAllWorkerViewDTO.getDept3id()))) {
                ptAllWorkerViewDTO.setDept3name(commService.getDept(ptAllWorkerViewDTO.getDept3id()).getDeptName());
            }
            if (!StringUtils.isEmpty(ptAllWorkerViewDTO.getDept1id()) && !ObjectUtils.isEmpty(commService.getDept(ptAllWorkerViewDTO.getDept4id()))) {
                ptAllWorkerViewDTO.setDept4name(commService.getDept(ptAllWorkerViewDTO.getDept4id()).getDeptName());
            }
            list2.add(ptAllWorkerViewDTO);
        });
        return list2;
    }

    /**
     * @title: selectByDto
     * @description: 精确查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<PtAllWorkerDTO> selectByDto(PtAllWorkerDTO dto) {
        //List<PtAllWorker> list = ptAllWorkerMapper.selectByExample(initExample(dto));
        List<PtAllWorker> list = ptAllWorkerMapper.queryList(JSONObject.parseObject(JSONObject.toJSONString(dto), PtAllWorker.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), PtAllWorkerDTO.class);
    }

    /**
     * @title: insertDto
     * @description: 插入操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer insertDto(PtAllWorkerDTO dto) {
        //if (null == dto.getId() || "".equals(dto.getId())) {
        //    String pkId = idWorker.nextId() + "";
        //    dto.setId(pkId);
        //}
        return ptAllWorkerMapper.insertPtAllWorker(JSONObject.parseObject(JSON.toJSONString(dto), PtAllWorker.class));
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer updateDto(PtAllWorkerDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        return ptAllWorkerMapper.updatePtAllWorker(JSONObject.parseObject(JSON.toJSONString(dto), PtAllWorker.class));
        //return ptAllWorkerMapper.updateByPrimaryKey(JSONObject.parseObject(JSON.toJSONString(dto), PtAllWorker.class));
        //} else {
        //    return 0;
        //}
    }

    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer deleteDto(PtAllWorkerDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
        return ptAllWorkerMapper.deletePtAllWorker(JSONObject.parseObject(JSON.toJSONString(dto), PtAllWorker.class));
        //return ptAllWorkerMapper.deleteByPrimaryKey(dto.getId());
        //} else {
        //    return 0;
        //}
    }


    /**
     * @title: initFuzzyExample
     * @description: 初始化 模糊查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    private Example initFuzzyExample(PtAllWorkerDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(PtAllWorker.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getWorkerId() && !"".equals(dto.getWorkerId())) {
                criteriaName.andLike("WorkerId", "%" + dto.getWorkerId() + "%");
            }
            if (null != dto.getDomainAccount() && !"".equals(dto.getDomainAccount())) {
                criteriaName.andLike("DomainAccount", "%" + dto.getDomainAccount() + "%");
            }
            if (null != dto.getWorkerName() && !"".equals(dto.getWorkerName())) {
                criteriaName.andLike("WorkerName", "%" + dto.getWorkerName() + "%");
            }
            if (null != dto.getDisplayName() && !"".equals(dto.getDisplayName())) {
                criteriaName.andLike("DisplayName", "%" + dto.getDisplayName() + "%");
            }
            if (null != dto.getDept1id() && !"".equals(dto.getDept1id())) {
                criteriaName.andLike("Dept1id", "%" + dto.getDept1id() + "%");
            }
            if (null != dto.getDept2id() && !"".equals(dto.getDept2id())) {
                criteriaName.andLike("Dept2id", "%" + dto.getDept2id() + "%");
            }
            if (null != dto.getDept3id() && !"".equals(dto.getDept3id())) {
                criteriaName.andLike("Dept3id", "%" + dto.getDept3id() + "%");
            }
            if (null != dto.getDept4id() && !"".equals(dto.getDept4id())) {
                criteriaName.andLike("Dept4id", "%" + dto.getDept4id() + "%");
            }
            if (null != dto.getDirectDeptId() && !"".equals(dto.getDirectDeptId())) {
                criteriaName.andLike("DirectDeptId", "%" + dto.getDirectDeptId() + "%");
            }
            if (null != dto.getPostType() && !"".equals(dto.getPostType())) {
                criteriaName.andLike("PostType", "%" + dto.getPostType() + "%");
            }
            if (null != dto.getPostLevel() && !"".equals(dto.getPostLevel())) {
                criteriaName.andLike("PostLevel", "%" + dto.getPostLevel() + "%");
            }
            if (null != dto.getPostTypeLevel() && !"".equals(dto.getPostTypeLevel())) {
                criteriaName.andLike("PostTypeLevel", "%" + dto.getPostTypeLevel() + "%");
            }
            if (null != dto.getJobType() && !"".equals(dto.getJobType())) {
                criteriaName.andLike("JobType", "%" + dto.getJobType() + "%");
            }
            if (null != dto.getJobLevel() && !"".equals(dto.getJobLevel())) {
                criteriaName.andLike("JobLevel", "%" + dto.getJobLevel() + "%");
            }
            if (null != dto.getJobLevelName() && !"".equals(dto.getJobLevelName())) {
                criteriaName.andLike("JobLevelName", "%" + dto.getJobLevelName() + "%");
            }
            if (null != dto.getJobTypeLevel() && !"".equals(dto.getJobTypeLevel())) {
                criteriaName.andLike("JobTypeLevel", "%" + dto.getJobTypeLevel() + "%");
            }
            if (null != dto.getSyncTime() && !"".equals(dto.getSyncTime())) {
                criteriaName.andLike("SyncTime", "%" + dto.getSyncTime() + "%");
            }
            if (null != dto.getEmail() && !"".equals(dto.getEmail())) {
                criteriaName.andLike("Email", "%" + dto.getEmail() + "%");
            }
            if (null != dto.getPhoneNo() && !"".equals(dto.getPhoneNo())) {
                criteriaName.andLike("PhoneNo", "%" + dto.getPhoneNo() + "%");
            }
            if (null != dto.getLeaderLevel() && !"".equals(dto.getLeaderLevel())) {
                criteriaName.andLike("LeaderLevel", "%" + dto.getLeaderLevel() + "%");
            }
            if (null != dto.getJoinDate() && !"".equals(dto.getJoinDate())) {
                criteriaName.andLike("JoinDate", "%" + dto.getJoinDate() + "%");
            }
            if (null != dto.getAge() && !"".equals(dto.getAge())) {
                criteriaName.andLike("Age", "%" + dto.getAge() + "%");
            }
            if (null != dto.getLockFlag() && !"".equals(dto.getLockFlag())) {
                criteriaName.andLike("LockFlag", "%" + dto.getLockFlag() + "%");
            }
            if (null != dto.getLockAccount() && !"".equals(dto.getLockAccount())) {
                criteriaName.andLike("LockAccount", "%" + dto.getLockAccount() + "%");
            }
        }
        return example;
    }

    /**
     * @title: initExample
     * @description: 初始化 精确查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-03-14
     * @version: 1.0
     * @author: l22886
     */
    private Example initExample(PtAllWorkerDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(PtAllWorker.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getWorkerId() && !"".equals(dto.getWorkerId())) {
                criteriaName.andEqualTo("WorkerId", dto.getWorkerId());
            }
            if (null != dto.getDomainAccount() && !"".equals(dto.getDomainAccount())) {
                criteriaName.andEqualTo("DomainAccount", dto.getDomainAccount());
            }
            if (null != dto.getWorkerName() && !"".equals(dto.getWorkerName())) {
                criteriaName.andEqualTo("WorkerName", dto.getWorkerName());
            }
            if (null != dto.getDisplayName() && !"".equals(dto.getDisplayName())) {
                criteriaName.andEqualTo("DisplayName", dto.getDisplayName());
            }
            if (null != dto.getDept1id() && !"".equals(dto.getDept1id())) {
                criteriaName.andEqualTo("Dept1id", dto.getDept1id());
            }
            if (null != dto.getDept2id() && !"".equals(dto.getDept2id())) {
                criteriaName.andEqualTo("Dept2id", dto.getDept2id());
            }
            if (null != dto.getDept3id() && !"".equals(dto.getDept3id())) {
                criteriaName.andEqualTo("Dept3id", dto.getDept3id());
            }
            if (null != dto.getDept4id() && !"".equals(dto.getDept4id())) {
                criteriaName.andEqualTo("Dept4id", dto.getDept4id());
            }
            if (null != dto.getDirectDeptId() && !"".equals(dto.getDirectDeptId())) {
                criteriaName.andEqualTo("DirectDeptId", dto.getDirectDeptId());
            }
            if (null != dto.getPostType() && !"".equals(dto.getPostType())) {
                criteriaName.andEqualTo("PostType", dto.getPostType());
            }
            if (null != dto.getPostLevel() && !"".equals(dto.getPostLevel())) {
                criteriaName.andEqualTo("PostLevel", dto.getPostLevel());
            }
            if (null != dto.getPostTypeLevel() && !"".equals(dto.getPostTypeLevel())) {
                criteriaName.andEqualTo("PostTypeLevel", dto.getPostTypeLevel());
            }
            if (null != dto.getJobType() && !"".equals(dto.getJobType())) {
                criteriaName.andEqualTo("JobType", dto.getJobType());
            }
            if (null != dto.getJobLevel() && !"".equals(dto.getJobLevel())) {
                criteriaName.andEqualTo("JobLevel", dto.getJobLevel());
            }
            if (null != dto.getJobLevelName() && !"".equals(dto.getJobLevelName())) {
                criteriaName.andEqualTo("JobLevelName", dto.getJobLevelName());
            }
            if (null != dto.getJobTypeLevel() && !"".equals(dto.getJobTypeLevel())) {
                criteriaName.andEqualTo("JobTypeLevel", dto.getJobTypeLevel());
            }
            if (null != dto.getSyncTime() && !"".equals(dto.getSyncTime())) {
                criteriaName.andEqualTo("SyncTime", dto.getSyncTime());
            }
            if (null != dto.getEmail() && !"".equals(dto.getEmail())) {
                criteriaName.andEqualTo("Email", dto.getEmail());
            }
            if (null != dto.getPhoneNo() && !"".equals(dto.getPhoneNo())) {
                criteriaName.andEqualTo("PhoneNo", dto.getPhoneNo());
            }
            if (null != dto.getLeaderLevel() && !"".equals(dto.getLeaderLevel())) {
                criteriaName.andEqualTo("LeaderLevel", dto.getLeaderLevel());
            }
            if (null != dto.getJoinDate() && !"".equals(dto.getJoinDate())) {
                criteriaName.andEqualTo("JoinDate", dto.getJoinDate());
            }
            if (null != dto.getAge() && !"".equals(dto.getAge())) {
                criteriaName.andEqualTo("Age", dto.getAge());
            }
            if (null != dto.getLockFlag() && !"".equals(dto.getLockFlag())) {
                criteriaName.andEqualTo("LockFlag", dto.getLockFlag());
            }
            if (null != dto.getLockAccount() && !"".equals(dto.getLockAccount())) {
                criteriaName.andEqualTo("LockAccount", dto.getLockAccount());
            }
        }
        return example;
    }

    //供前端人员组件使用的人员搜索
    @Override
    public List<PtAllWorker> searchWorker(String keyword) {
        if (!StringUtils.hasText(keyword)) {
            return new ArrayList<>();
        }
        QueryWrapper<PtAllWorker> queryWrapper = new QueryWrapper<>();
        String[] keywordArr = keyword.split(",");
        for (String key : keywordArr) {
            int i = judgeStr(key);
            if (i == 1) {
                queryWrapper.or(o -> o.like("worker_id", key));
            } else if (i == 2) {
                queryWrapper.or(o -> o.like("display_name", key));
            } else if (i == 3) {
                queryWrapper.or(o -> o.like("worker_name", key));
            }else if (i == 4){
                queryWrapper.or(o -> o.like("domain_account", key));
            }
        }
        queryWrapper.orderByAsc("worker_id").last("limit 20");
        List<PtAllWorker> workerList = list(queryWrapper);
        workerList.forEach(s -> {
            PtDept dept = DeptCache.getPtDeptByDeptId(s.getDirectDeptId());
            if (Objects.nonNull(dept)) {
                s.setDirectDeptName(dept.getDeptName());
            }
        });
        if (workerList.size() == 0) {
            for (String key : keywordArr) {
                int i = judgeStr(key);
                if (i == 1 && key.length() == 5) {
                    Map<String, String> map = commService.queryCooperativeWorker(key);
                    if (map != null) {
                        PtAllWorker ptAllWorker = new PtAllWorker();
                        ptAllWorker.setWorkerId(map.get("emp_code"));
                        ptAllWorker.setWorkerName(map.get("emp_name"));
                        workerList.add(ptAllWorker);

                        //是合作员工，同时加入sdAllWorker
                        ptAllWorker.setDomainAccount(map.get("domain_account"));
                        String directDeptId = "";
                        if (!StringUtils.isEmpty(map.get("dept1_code"))) {
                            ptAllWorker.setDept1id(Integer.parseInt(map.get("dept1_code")));
                            directDeptId = map.get("dept1_code");
                        }
                        if (!StringUtils.isEmpty(map.get("dept2_code"))) {
                            ptAllWorker.setDept2id(Integer.parseInt(map.get("dept2_code")));
                            directDeptId = map.get("dept2_code");
                        }
                        if (!StringUtils.isEmpty(map.get("dept3_code"))) {
                            ptAllWorker.setDept3id(Integer.parseInt(map.get("dept3_code")));
                            directDeptId = map.get("dept3_code");
                        }
                        if (!StringUtils.isEmpty(map.get("dept4_code"))) {
                            ptAllWorker.setDept4id(Integer.parseInt(map.get("dept4_code")));
                            directDeptId = map.get("dept3_code");
                        }
                        ptAllWorker.setDirectDeptId(Integer.parseInt(directDeptId));
                        if (!StringUtils.isEmpty(map.get("display_name"))) {
                            ptAllWorker.setDisplayName(map.get("display_name"));
                        }
                        if (!StringUtils.isEmpty(map.get("email"))) {
                            ptAllWorker.setEmail(map.get("email"));
                        }
                        ptAllWorker.setSyncTime(new Date());
                        ptAllWorker.setWorkerType(2);//合作员工
                        ptAllWorkerMapper.insertPtAllWorker(ptAllWorker);
                        commService.setAllWorkerByWorkerId(ptAllWorker);
                        log.info("加入合作员工：" + map.get("emp_code") + "至人员总表。");
                    }
                }
            }
        }
        return workerList;
    }

    public Integer judgeStr(String keyWords) {
        Pattern pattern1 = Pattern.compile("[0-9]*");
        Matcher matcher1 = pattern1.matcher(keyWords);
        if (matcher1.matches()) {
            return 1;
        } else {
            Pattern pattern2 = Pattern.compile("[a-zA-Z]+$");
            Matcher matcher2 = pattern2.matcher(keyWords);
            if (matcher2.matches()) {
                return 2;
            } else {
                Pattern pattern3 = Pattern.compile("[\\u4e00-\\u9fa5]{0,}$");
                Matcher matcher3 = pattern3.matcher(keyWords);
                if (matcher3.matches()) {
                    return 3;
                } else {
                    Pattern pattern4 = Pattern.compile("^[a-zA-Z][a-zA-Z0-9]*[0-9]$");
                    Matcher matcher4 = pattern4.matcher(keyWords);
                    if (matcher4.matches()){
                        return 4;
                    }else {
                        return -1;
                    }
                }
            }
        }

    }


    //人员更新方案；
    // 更新正式员工，离职员工不删除，只改状态；合作员工不动
    @Override
    @Transactional
    public void syncWorker() {

        try {
            String workerDatas = eosSyncDataClient.syncAllWorker("Bearer " + userUtils.getToken(inventoryAccount, inventoryPassword));
            Result<List<PtAllWorkerViewDTO>> result = JSON.parseObject(workerDatas, new TypeReference<Result<List<PtAllWorkerViewDTO>>>() {
            });

            List<PtAllWorkerViewDTO> ptAllWorkerViewDTOList = result.getData();
            List<PtAllWorker> ptAllWorkerList = new ArrayList<>();
//            List<PtAllWorker> ptAllWorkersListEx = ptAllWorkerMapper.selectList(new QueryWrapper<PtAllWorker>().eq("worker_type",1));
            update(new UpdateWrapper<PtAllWorker>()
                    .eq("worker_type", 1)
                    .set("worker_status", 2));

            for (PtAllWorkerViewDTO workerViewDTO : ptAllWorkerViewDTOList) {
                PtAllWorker worker = new PtAllWorker();
                BeanUtils.copyProperties(workerViewDTO, worker);

                worker.setSyncTime(new Date());
                worker.setWorkerType(1);//正式员工
                worker.setWorkerStatus(1);//在职
                ptAllWorkerList.add(worker);
            }
            //remove(new QueryWrapper<>());
            saveOrUpdateBatch(ptAllWorkerList);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppBusinessException("同步失败");
        }
    }

    //添加合作员工至ptAllWorker
    @Override
    public Integer addCooperativeWorker(PtAllWorkerDTO ptAllWorkerDTO) {
//        PtAllWorker ptAllWorkerExist = commService.getAllWorkerByWorkerId(ptAllWorkerDTO.getWorkerId());
        if (StringUtils.isEmpty(ptAllWorkerDTO.getWorkerId())) {
            return 0;
        }
//        PtAllWorker ptAllWorkerExist = ptAllWorkerMapper.selectOne(new QueryWrapper<PtAllWorker>().eq("worker_id",ptAllWorkerDTO.getWorkerId()));
        PtAllWorker ptAllWorkerExist = commService.getAllWorkerByWorkerId(ptAllWorkerDTO.getWorkerId());
        if (!ObjectUtils.isEmpty(ptAllWorkerExist)) {
            return 0;
        }
        Map<String, String> map = commService.queryCooperativeWorker(ptAllWorkerDTO.getWorkerId());
        PtAllWorker ptAllWorker = new PtAllWorker();
        if (map != null) {
            ptAllWorker.setWorkerId(map.get("emp_code"));
            ptAllWorker.setWorkerName(map.get("emp_name"));
            ptAllWorker.setDomainAccount(map.get("domain_account"));
            String directDeptId = "";
            if (!StringUtils.isEmpty(map.get("dept1_code"))) {
                ptAllWorker.setDept1id(Integer.parseInt(map.get("dept1_code")));
                directDeptId = map.get("dept1_code");
            }
            if (!StringUtils.isEmpty(map.get("dept2_code"))) {
                ptAllWorker.setDept2id(Integer.parseInt(map.get("dept2_code")));
                directDeptId = map.get("dept2_code");
            }
            if (!StringUtils.isEmpty(map.get("dept3_code"))) {
                ptAllWorker.setDept3id(Integer.parseInt(map.get("dept3_code")));
                directDeptId = map.get("dept3_code");
            }
            if (!StringUtils.isEmpty(map.get("dept4_code"))) {
                ptAllWorker.setDept4id(Integer.parseInt(map.get("dept4_code")));
                directDeptId = map.get("dept3_code");
            }
            ptAllWorker.setDirectDeptId(Integer.parseInt(directDeptId));
            if (!StringUtils.isEmpty(map.get("display_name"))) {
                ptAllWorker.setDisplayName(map.get("display_name"));
            }
            if (!StringUtils.isEmpty(map.get("email"))) {
                ptAllWorker.setEmail(map.get("email"));
            }
            ptAllWorker.setSyncTime(new Date());
        }
        commService.setAllWorkerByWorkerId(ptAllWorker);//更新缓存
        return ptAllWorkerMapper.insertPtAllWorker(ptAllWorker);
    }


    /**
     * @title: importAllWorker
     * @description:
     * @params:
     * @return:
     * @createTime: 2022-04-14
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public Integer importAllWorker(MultipartFile file) {
        String fileContent = commService.parseExcelByTemplate("ALL_WORKER_IMPORT", file);
        JSONArray jsonArray = JSONArray.parseArray(fileContent);
        // List<SdUserDTO> sdUserDTOS = JSONArray.parseArray(fileContent, SdUserDTO.class);
        int i = 0;
        for (Object jsonObj : jsonArray) {
            JSONObject jsonObject = JSONObject.parseObject(jsonObj.toString());
            PtAllWorkerDTO ptAllWorkerDTO = JSONObject.parseObject(String.valueOf(jsonObject), PtAllWorkerDTO.class);
            i = i + addCooperativeWorker(ptAllWorkerDTO);
        }
        return i;
    }


    /**
     * 列表分页查询基础人员信息
     *
     * @param pageQuery 入参
     * @param appId     租户id
     * @return 列表分页查询基础人员信息
     */
    @Override
    public IPage<PtAllWorkerVO> queryPage(PageQuery<PtAllWorkerDTO> pageQuery, String appId) {

        List<PtAllWorkerViewDTO> list2 = new ArrayList<>();
        // 设置分页
        Page<PtAllWorker> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        PtAllWorkerDTO dto = pageQuery.getCondition();
        // 添加搜索条件
        QueryWrapper<PtAllWorker> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(StringUtils.hasText(dto.getWorkerId()), PtAllWorker::getWorkerId, dto.getWorkerId())
                .eq(StringUtils.hasText(dto.getDomainAccount()), PtAllWorker::getDomainAccount, dto.getDomainAccount())
                .like(StringUtils.hasText(dto.getDisplayName()), PtAllWorker::getDisplayName, dto.getDisplayName())
                .like(StringUtils.hasText(dto.getWorkerName()), PtAllWorker::getWorkerName, dto.getWorkerName())
                .eq(Objects.nonNull(dto.getWorkerStatus()), PtAllWorker::getWorkerStatus, dto.getWorkerStatus())
                .eq(Objects.nonNull(dto.getWorkerType()), PtAllWorker::getWorkerType, dto.getWorkerType());
        // 添加排序
        MybatisUtils.setOrderBy(page, pageQuery.getSortList());
        // 查询
        Page<PtAllWorker> sysMdmEmpPage = ptAllWorkerMapper.selectPage(page, queryWrapper);
        // 转化成vo
        List<PtAllWorkerVO> sysMdmEmpVOList = BeanUtil.copyToList(sysMdmEmpPage.getRecords(), PtAllWorkerVO.class);
        sysMdmEmpVOList.forEach(ptAllWorker -> {
            if (!StringUtils.isEmpty(ptAllWorker.getDept1id())) {
                ptAllWorker.setDept1name(commService.getDeptName(ptAllWorker.getDept1id()));
            }
            if (!StringUtils.isEmpty(ptAllWorker.getDept2id())) {
                ptAllWorker.setDept2name(commService.getDeptName(ptAllWorker.getDept2id()));
            }
            if (!StringUtils.isEmpty(ptAllWorker.getDept3id())) {
                ptAllWorker.setDept3name(commService.getDeptName(ptAllWorker.getDept3id()));
            }
            if (!StringUtils.isEmpty(ptAllWorker.getDept4id())) {
                ptAllWorker.setDept4name(commService.getDeptName(ptAllWorker.getDept4id()));
            }
            String account = ptAllWorker.getDomainAccount();
            if(StringUtils.hasText(account) && StringUtils.hasText(appId)){
                List<EosRoleClientDTO> roles = eosAuthService.getRolesByAccount(account, appId);
                if(CollectionUtils.isNotEmpty(roles)){
                    ptAllWorker.setEosRoles(roles);
                }
            }
        });
        // 转化IPage
        return MybatisUtils.changeIPage(sysMdmEmpPage, sysMdmEmpVOList);
    }

    @Override
    public List<PtAllWorker> queryWorkerInfoByDomain(List<String> workerIds) {
        if(workerIds.size()==0){
            return new ArrayList<>();
        }
        List<PtAllWorker> ptAllWorkers = ptAllWorkerMapper.selectList(new QueryWrapper<PtAllWorker>().lambda().in(PtAllWorker::getWorkerId, workerIds));
        return ptAllWorkers;
    }

}
